import cookies from './util.cookies'
import db from './util.db'
import log from './util.log'

const util = {
  cookies,
  db,
  log
}

/**
 * @description 更新标题
 * @param {String} title 标题
 */
util.title = function (titleText) {
  const processTitle = process.env.VUE_APP_TITLE || 'D2Admin'
  window.document.title = `${processTitle}${titleText ? ` | ${titleText}` : ''}`
}

/**
 * @description 打开新页面
 * @param {String} url 地址
 */
util.open = function (url) {
  var a = document.createElement('a')
  a.setAttribute('href', url)
  a.setAttribute('target', '_blank')
  a.setAttribute('id', 'd2admin-link-temp')
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(document.getElementById('d2admin-link-temp'))
}


Date.prototype.format = function (format) {
  var o = {
    "M+": this.getMonth() + 1, // month
    "d+": this.getDate(), // day
    "h+": this.getHours(), // hour
    "m+": this.getMinutes(), // minute
    "s+": this.getSeconds(), // second
    "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
    S: this.getMilliseconds() // millisecond
  };
  if (/(y+)/.test(format)) {
    format = format.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return format;
};

// eslint-disable-next-line
String.prototype.format = function (placeholders) {
  var s = this;
  for (var propertyName in placeholders) {
    var re = new RegExp("{" + propertyName + "}", "gm");
    s = s.replace(re, placeholders[propertyName]);
  }
  return s;
};

window.getCookie = function(name) {
  var arr,
    reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if ((arr = document.cookie.match(reg))) return decodeURI(arr[2]);
  else return null;
};
/**
 * 计算n天前/后的日期
 * @param n
 * @returns {String}
 */
util.getBeforeDate= function (strDate, n) {
  return new Date(
    new Date(strDate).setDate(new Date(strDate).getDate() + n)
  ).format("yyyy-MM-dd");
}

util.scrollByEl= function (el) {
  el.scrollIntoView({
    block: 'start',
    behavior: 'smooth'
  })
}

util.scrollToTop = function (el) {
  el.scrollTo({
    top:0,
    behavior:'smooth'
  })
}

export default util
